package com.UBC417.termproject.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.UBC417.termproject.Data.User;

@SuppressWarnings("serial")
public class SubscribeServlet extends HttpServlet{
	private static final Logger log = Logger.getLogger(SubscribeServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		// Get parameters		
		String userID = req.getParameter("emailSignup");
		String userName = req.getParameter("nameSignup");
		String password = req.getParameter("passwordSignup");
		String type = req.getParameter ("typeSignup");
		
		String forwardTo = "/account.jsp";
				
		log.info("user: "+ userID);
		log.info ("name: "+ userName);
		log.info ("pwd: "+ password);
		log.info ("type: "+ type);
		
		
		if (!User.Signup(userName, userID, password, type)){
			log.info("ENTER UNIQUE EMAIL!!!");
			resp.setContentType("text/html");
	        PrintWriter out = resp.getWriter();
	        out.println("<html>");
	        out.println("<head><title>Fail to Subscribe!</title></head>");
	        out.println("<body>");
	        out.println("<h1>Subscription Failure</h1>");
	        out.println("Your email seems to be subscribed already... Please try again!<br>");
	        out.println("<a HREF='javascript:history.back()'>Back</a>");
	        out.println("</body></html>");
		}else{
			//http session
			HttpSession session = req.getSession();
			session.setAttribute("id",userID);
			session.setAttribute("type", type);
			session.setMaxInactiveInterval(3600); // inactive for 1 hour
			
			// check user type
			if (type.equals("Seller")){
				forwardTo ="/seller.jsp";
			}else{
				forwardTo="/buyer.jsp";
				
			}
			// redirect to user page
//			ServletContext sc = getServletContext();
//			RequestDispatcher rd = sc.getRequestDispatcher(forwardTo);
//			rd.forward(req, resp);
			resp.sendRedirect(forwardTo);
		}		
	}	
	
}
